<template>
  <div class="login">
    <LoginLeftView></LoginLeftView>

    <div class="right-wrap">
      <div class="top-right-wrap">
        <div v-if="shouldShowThemeToggle" class="btn theme-btn" @click="themeAnimation">
          <i class="iconfont-sys">
            {{ isDark ? '&#xe6b5;' : '&#xe725;' }}
          </i>
        </div>
      </div>
      <div class="header">
        <ArtLogo class="icon" />
        <h1>{{ systemName }}</h1>
      </div>
      <div class="login-wrap">
        <div class="form">
          <h3 class="title">{{ '欢迎回来' }}</h3>
          <p class="sub-title">{{ '输入您的账号和密码登录' }}</p>
          <ElForm
            ref="formRef"
            :model="formData"
            :rules="rules"
            @keyup.enter="handleSubmit"
            style="margin-top: 25px"
          >
            <ElFormItem prop="tenant_code">
              <ElSelect
                v-model="formData.tenant_code"
                :placeholder="tenantPlaceholder"
                filterable
                remote
                :clearable="!tenantLocked"
                :disabled="tenantLocked"
                :remote-method="remoteSearchTenant"
                :loading="tenantLoading"
              >
                <ElOption
                  v-for="item in tenantOptions"
                  :key="item.code"
                  :label="formatTenantLabel(item)"
                  :value="item.code"
                />
              </ElSelect>
            </ElFormItem>
            <ElFormItem prop="account">
              <ElInput v-model.trim="formData.account" :placeholder="accountPlaceholder" />
            </ElFormItem>
            <ElFormItem prop="password">
              <ElInput
                :placeholder="passwordPlaceholder"
                v-model.trim="formData.password"
                type="password"
                radius="8px"
                autocomplete="off"
                show-password
              />
            </ElFormItem>
            <ElFormItem prop="captcha">
              <div class="captcha-wrap">
                <ElInput v-model.trim="formData.captcha" :placeholder="captchaPlaceholder" />
                <img
                  v-if="captchaImageUrl"
                  :src="captchaImageUrl"
                  class="captcha-image"
                  alt="captcha"
                  @click="refreshCaptcha"
                  @error="handleImageError"
                />
                <div v-else class="captcha-loading" @click="refreshCaptcha">
                  {{ captchaLoadingText }}
                </div>
              </div>
            </ElFormItem>

            <div class="forget-password">
              <ElCheckbox v-model="formData.rememberPassword">{{ '记住密码' }}</ElCheckbox>
              <RouterLink :to="RoutesAlias.ForgetPassword">{{ '忘记密码' }}</RouterLink>
            </div>

            <div style="margin-top: 30px">
              <ElButton
                class="login-btn"
                type="primary"
                @click="handleSubmit"
                :loading="loading"
                v-ripple
              >
                {{ '登录' }}
              </ElButton>
            </div>

            <!-- 内部系统不提供注册提示，移除“还没有账号？请联系管理员开通” -->
          </ElForm>
        </div>
      </div>
      <!-- 登录页不提供二维码弹窗入口（忘记密码页提供二维码） -->
    </div>
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, reactive, ref } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { storeToRefs } from 'pinia'
  import AppConfig from '@/config'
  import { RoutesAlias } from '@/router/routesAlias'
  import { ElNotification, ElMessage } from 'element-plus'
  import { useUserStore } from '@/store/modules/user'
  import { themeAnimation } from '@/utils/theme/animation'
  import { fetchLogin, fetchGetUserInfo, fetchCaptcha } from '@/api/auth'
  import { useHeaderBar } from '@/composables/useHeaderBar'
  import { useSettingStore } from '@/store/modules/setting'
  import type { FormInstance, FormRules } from 'element-plus'

  defineOptions({ name: 'Login' })

  const settingStore = useSettingStore()
  const { isDark } = storeToRefs(settingStore)
  const { shouldShowThemeToggle } = useHeaderBar()

  const userStore = useUserStore()
  const router = useRouter()
  const route = useRoute()

  const systemName = AppConfig.systemInfo.name
  const formRef = ref<FormInstance>()
  const tenantLocked = ref(false)

  const formData = reactive({
    tenant_code: '',
    account: '',
    password: '',
    captcha: '',
    rememberPassword: true
  })

  const tenantPlaceholder = computed(() => '请输入租户编码')
  const accountPlaceholder = computed(() => '请输入账号')
  const passwordPlaceholder = computed(() => '请输入密码')
  const captchaPlaceholder = computed(() => '请输入验证码')
  const captchaLoadingText = computed(() => '加载中...')

  const rules = computed<FormRules>(() => ({
    tenant_code: [{ required: true, message: tenantPlaceholder.value, trigger: 'change' }],
    account: [{ required: true, message: accountPlaceholder.value, trigger: 'blur' }],
    password: [{ required: true, message: passwordPlaceholder.value, trigger: 'blur' }],
    captcha: [{ required: true, message: captchaPlaceholder.value, trigger: 'blur' }]
  }))

  // 登录页租户下拉搜索
  const tenantOptions = ref<Api.Auth.TenantItem[]>([])
  const tenantLoading = ref(false)
  const MIN_LEN = 3

  const doSearchTenant = async (query: string) => {
    if (!query || query.trim().length < MIN_LEN) {
      tenantOptions.value = []
      return
    }
    tenantLoading.value = true
    try {
      const { searchTenant } = await import('@/api/auth')
      const list = await searchTenant(query.trim())
      tenantOptions.value = Array.isArray(list) ? list : []
    } catch (error) {
      console.error('[Login] search tenant failed:', error)
      tenantOptions.value = []
    } finally {
      tenantLoading.value = false
    }
  }

  const remoteSearchTenant = useDebounceFn((query: string) => doSearchTenant(query), 300)
  const formatTenantLabel = (item: Api.Auth.TenantItem) => `${item.code} - ${item.name}`

  const loading = ref(false)
  const captchaImageUrl = ref('')
  const captchaId = ref('')
  // 登录页不再提供二维码弹窗逻辑（忘记密码页提供二维码联系管理员）

  const refreshCaptcha = async () => {
    try {
      const captcha = await fetchCaptcha(80, 240)
      captchaImageUrl.value = captcha.image
      captchaId.value = (captcha as any).captcha_id || ''
    } catch (error) {
      console.error('[Login] refreshCaptcha error:', error)
      ElMessage.error('验证码获取失败')
    }
  }

  const handleImageError = () => {
    ElMessage.error('验证码加载失败，请点击刷新')
    captchaImageUrl.value = ''
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    const valid = await formRef.value.validate().catch(() => false)
    if (!valid) return

    loading.value = true
    try {
      const loginRes = await fetchLogin({
        tenant_code: formData.tenant_code,
        account: formData.account,
        password: formData.password,
        captcha: formData.captcha,
        captcha_id: captchaId.value
      })

      if (!loginRes.token) {
        throw new Error('登录失败，请稍后重试')
      }

      userStore.setToken(loginRes.token)
      userStore.setCurrentTenantCode(formData.tenant_code)
      userStore.setLoginStatus(true)

      const userInfo = await fetchGetUserInfo().catch((error) => {
        console.error('[Login] fetch user info error:', error)
        return undefined
      })

      if (userInfo) {
        userStore.setUserInfo(userInfo)
        if (userInfo.tenant) {
          userStore.setTenantInfo(userInfo.tenant as Record<string, any>)
        }
        if (userInfo.tenantCode) {
          userStore.setCurrentTenantCode(userInfo.tenantCode)
        }
      }

      showLoginSuccessNotice()
      router.push('/')
    } catch (error) {
      const message = error instanceof Error ? error.message : ''
      ElMessage.error(message || '登录失败，请稍后重试')
      await refreshCaptcha()
    } finally {
      loading.value = false
    }
  }

  const showLoginSuccessNotice = () => {
    setTimeout(() => {
      ElNotification({
        title: '登录成功',
        type: 'success',
        duration: 2500,
        zIndex: 10000,
        message: `欢迎回来, ${systemName}!`
      })
    }, 150)
  }

  onMounted(async () => {
    refreshCaptcha()

    // 如果带有租户编码查询参数，则填充并锁定
    const q = route.query.tenant_code
    const queryTenant = typeof q === 'string' ? q : Array.isArray(q) ? q[0] : ''
    if (queryTenant) {
      formData.tenant_code = queryTenant
      tenantLocked.value = true
      // 可选：尝试预加载对应的下拉项以显示名称
      try {
        const { searchTenant } = await import('@/api/auth')
        const list = await searchTenant(queryTenant)
        if (Array.isArray(list) && list.length > 0) {
          tenantOptions.value = list
        }
      } catch {
        // 忽略预加载失败
        void 0
      }
    }
  })
</script>

<style lang="scss" scoped>
  @use './index';
</style>
